package com.itmuch.box.controller.front.member;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.itmuch.box.core.base.BaseController;
import com.itmuch.box.core.constant.ConstantsSession;
import com.itmuch.box.core.security.SubjectUtil;
import com.itmuch.box.domain.member.entity.Member;
import com.itmuch.box.domain.member.vo.MemberInfoVo;
import com.itmuch.box.service.config.ConfigService;
import com.itmuch.box.service.member.MemberService;
import com.itmuch.box.util.DozerUtil;

/**
 * 个人信息
 * @author zhouli
 */
@Controller
@RequestMapping("/member")
public class MemberCenterInfoController extends BaseController {
    @Resource
    private MemberService memberService;
    @Resource
    private ConfigService configService;

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public ModelAndView info() {
        Integer id = SubjectUtil.getSubjectId();
        Member member = this.memberService.findOne(id);

        return new ModelAndView("front/member/center/info").addObject("info", member);
    }

    @RequestMapping(value = "/info", method = RequestMethod.POST)
    public ModelAndView info(@Valid @ModelAttribute("info") MemberInfoVo vo, BindingResult result, RedirectAttributes ra, HttpServletRequest req,
            HttpSession session) {
        // JSR 校验成功
        if (!result.hasErrors()) {
            Integer id = SubjectUtil.getSubjectId();
            Member member = this.memberService.findOne(id);

            DozerUtil.map(vo, member);

            // 如果修改了头像, 更新下session
            String face = vo.getFace();
            if (!StringUtils.isEmpty(face)) {
                String attachDomain = this.configService.selectValueByKey("attach.domain");
                session.setAttribute(ConstantsSession.MEMBER_FACE, attachDomain + face);
            }

            this.memberService.update(member);

            ra.addFlashAttribute("msg", "修改成功");
            ra.addFlashAttribute("nextUrl", req.getContextPath() + "/member/info");
            return new ModelAndView(String.format("redirect:/%s", "success"));
        }
        // JSR 校验失败
        return new ModelAndView("front/member/center/info");
    }
}
